package com.yang.leather.common.store;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.tepando.upload.images.ImageSize;
import com.tepando.upload.images.ImageType;
import com.yang.leather.admin.pojo.ImgsDel;
import com.yang.leather.common.store.image.ImageScale;
import com.yang.leather.common.upload.ImageUploadType;
import com.yang.leather.common.util.Num62;
import com.yang.leather.core.Constant;


@Service("diskFileService")
public class FileService implements IFileService{
	private Logger log = LoggerFactory.getLogger(FileService.class);
	
	private ImageScale imageScale;
	
	/**
	 * 日期格式化对象，将当前日期格式化成yyyyMM格式，用于生成目录。
	 */
	public static final DateFormat pathDf = new SimpleDateFormat("yyyyMM/dd");
	/**
	 * 日期格式化对象，将当前日期格式化成ddHHmmss格式，用于生成文件名。
	 */
	public static final DateFormat nameDf = new SimpleDateFormat("ddHHmmss");
	
	public String store(File[] files, ImageType imgType,ImageUploadType uploadType) throws FileException{
		StringBuilder returnFile = new StringBuilder();
		try{
			for(File file : files){
				if(imgType.getSizes().size()==1){//图片生成一种规格
					ImageSize size = null;
					for(ImageSize tSize : imgType.getSizes().values()){
						size = tSize;
					}
					String filePath = this.genPathName(uploadType);
					String fileName = this.genFileName();
					returnFile.append(filePath).append(",").append(fileName).append(";");
					
					imageScale.resizeFix(file, new File(Constant.PROJECT_REAL_PATH + filePath+fileName+".jpg"), size.getWidth(), size.getHeight());
				}else{
					String filePath = this.genPathName(uploadType);
					String fileName = this.genFileName();
					for(ImageSize size : imgType.getSizes().values()){
						imageScale.resizeFix(file, new File(Constant.PROJECT_REAL_PATH + filePath+fileName+"_"+size.getSizeId()+".jpg"), size.getWidth(), size.getHeight());
					}
					returnFile.append(filePath).append(",").append(fileName).append(";");
				}
			}
			
			return returnFile.toString();
		}catch(Exception e){
			throw new FileException(e,"");
		}
	}
	
	public void deleteFile(List<ImgsDel> list) throws FileException{
		try{
			for(ImgsDel del : list){
				String filePath = del.getFilePath().replace('/', File.separatorChar);
				final String fileName = del.getFileName();
				
				File fd = new File(Constant.PROJECT_REAL_PATH + filePath);
				if(fd.exists() && fd.isDirectory()){
					File[] delFiles = fd.listFiles(new FileFilter(){
						public boolean accept(File pathname) {
							return pathname.getName().indexOf(fileName)>-1;
					}});
					
					if(delFiles!=null){
						if(delFiles.length == fd.listFiles().length){
							try {
								org.apache.commons.io.FileUtils.deleteDirectory(fd);
							} catch (IOException e) {
								log.info(e.getMessage());
							}
						}else{
							for(File delF : delFiles){
								org.apache.commons.io.FileUtils.deleteQuietly(delF);
							}
						}
					}
				}
			}
		}catch(Exception e){
			throw new FileException(e,"");
		}
	}
	
	/**
	 * 生成当前年月格式的文件路径
	 * 
	 * yyyyMM 200806
	 * 
	 * @return
	 */
	public String genPathName(ImageUploadType uploadType) {
		return 	Constant.FILE_CENTER_PATH.concat("/")
				.concat(uploadType.getType())
				.concat("/").concat(pathDf.format(new Date()))
				.concat("/").concat(nameDf.format(new Date())).concat("/");
	}
	
	/**
	 * 生产以当前日、时间开头加4位随机数的文件名
	 * 
	 * ddHHmmss 03102230
	 * 
	 * @return 10位长度文件名
	 */
	public String genFileName() {
		return nameDf.format(new Date())
				+ RandomStringUtils.random(4, Num62.N36_CHARS);
	}


	public ImageScale getImageScale() {
		return imageScale;
	}

	@Autowired
	public void setImageScale(@Qualifier("imageScale")
			ImageScale imageScale) {
		this.imageScale = imageScale;
	}
}
